package com.zadetk.helpyou.net;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Handler;

import com.zadetk.helpyou.other.Const;
import com.zadetk.helpyou.utils.FileUtil;
import com.zadetk.helpyou.utils.VersionUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载apk
 */
public class LoadApkAsyncTask extends AsyncTask<String, Integer, Boolean> {
    public static final int LOAD_APK = 0X10;
    public static final String UPDATE_APK_NAME = "HelpYou.apk";
    /**
     * mProgressDialog:进度条
     */
    private ProgressDialog progressDialog;
    private Context context;
    private Handler handler;

    public LoadApkAsyncTask(Context context, String progressMsg, Handler handler) {
        this.handler = handler;
        this.context = context;
        showInProgress(context, progressMsg, true, false);
    }

    @Override
    protected Boolean doInBackground(String... params) {

        return loadApk(context, progressDialog, params[0], Const.getSavePath(context),
                UPDATE_APK_NAME, params[1]);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        cancelInProgress();
        handler.obtainMessage(LOAD_APK, result).sendToTarget();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (null != progressDialog) {
            progressDialog.setProgress(values[0]);
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onCancelled(Boolean result) {
        super.onCancelled(result);
        handler.obtainMessage(LOAD_APK, result).sendToTarget();
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    /**
     * 函数名称 : showInProgress<br>
     * 功能描述 : 显示进度框 <p>
     * 参数及返回值说明：<br>
     *
     * @param context
     * @param text
     * @param bIndeterminate
     * @param bCancelable    void<br>
     */
    private void showInProgress(Context context, String text,
                                boolean bIndeterminate, boolean bCancelable) {
        synchronized (this) {
            if (progressDialog == null) {

                progressDialog = new ProgressDialog(context);
                progressDialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        progressDialog = null;
                    }
                });
                progressDialog
                        .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage(text);
                progressDialog.setMax(100);
                progressDialog.setIndeterminate(false);
                progressDialog.setCancelable(bCancelable);
                progressDialog.show();

            }
        }
    }

    /**
     * 函数名称 : cancelInProgress<br>
     * 功能描述 : 关闭进度对话框 <p>
     * 参数及返回值说明：<br>   void<br>
     */
    protected void cancelInProgress() {
        synchronized (this) {
            if (progressDialog != null) {
                progressDialog.cancel();
                progressDialog = null;
            }
        }
    }

    /**
     * 下载apk
     *
     * @param context
     * @param progressDialog    进度条
     * @param urlStr            apk下载地址
     * @param savePath          apk保存文件夹地址
     * @param name              apk保存在本地的名称
     * @param remoteVersionCode 远程服务器apk版本
     * @return
     * @date FionaLiu 2015年8月4日 下午3:06:36
     */
    private boolean loadApk(Context context, ProgressDialog progressDialog,
                            String urlStr, String savePath, String name,
                            String remoteVersionCode) {
        int leng = -1;
        File savaFile = new File(savePath);
        if (!savaFile.exists()) {
            savaFile.mkdirs();
        }
        File file = new File(savePath, name);
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            leng = conn.getContentLength();

            if (file.exists()) {
                if (((FileUtil.getFileSize(file) == leng) && VersionUtils
                        .getAppVersionCode(context, file.toString()) == Integer
                        .parseInt(remoteVersionCode))) {
                    if (null != progressDialog) {
                        for (int i = 0; i < 100; i++) {
                            publishProgress(i);
                            try {
                                Thread.sleep(30);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    return true;
                } else {
                    FileUtil.deleteFile(file);
                }
            }
            inputStream = conn.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            bufferedInputStream = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
                total += len;
                if (null != progressDialog) {
                    publishProgress((int) ((total / (float) leng) * 100));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (file.exists()) {
                FileUtil.deleteFile(file);
            }
        } finally {
            try {
                if (null != fileOutputStream) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != bufferedInputStream) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file.exists();
    }
}
